package com.colorlight.cloud.complete.entity.instructions;

import com.colorlight.cloud.common.exception.ParameterException;
import com.colorlight.cloud.common.model.ExceptionEnum;
import com.colorlight.cloud.complete.api.CompleteEntityScheduleActions;
import com.colorlight.cloud.complete.entity.po.ModuleTemperatureParam;
import com.colorlight.iot.proto.complete.instruction.CompleteInstruction;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;
import java.util.Objects;

/**
 * 模组温度控制
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Slf4j
public class SetModuleTemperatureControl implements CompleteEntityScheduleActions {

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @Builder
    public static class InputMsg implements Serializable {
        /**
         * 控制参数
         */
        private ModuleTemperatureParam param;
    }

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @Builder
    public static class OutputMsg implements Serializable {
        /**
         * 返回设置的控制参数
         */
        private ModuleTemperatureParam param;
    }

    private InputMsg input;
    private OutputMsg output;

    @Override
    public ByteString objectConvertBytes() {
        final CompleteInstruction.SetModuleTemperatureControl.InputMsg.Builder inputMsg =
                CompleteInstruction.SetModuleTemperatureControl.InputMsg.newBuilder();
        SetModuleTemperatureControl.InputMsg thisInput = this.getInput();
        inputMsg.setParam(thisInput.getParam().toProto());
        final CompleteInstruction.SetModuleTemperatureControl.Builder builder =
                CompleteInstruction.SetModuleTemperatureControl.newBuilder();
        builder.setInput(inputMsg);
        return builder.build().toByteString();
    }

    @Override
    public SetModuleTemperatureControl byteConvertObject(ByteString bytes) {
        CompleteInstruction.SetModuleTemperatureControl setModuleTemperatureControl = null;
        try {
            setModuleTemperatureControl = CompleteInstruction.SetModuleTemperatureControl.parseFrom(bytes);
        } catch (InvalidProtocolBufferException e) {
            log.error("", e);
        }
        if (Objects.isNull(setModuleTemperatureControl)) {
            throw new ParameterException(ExceptionEnum.MSG_PARAMETER_EXCEPTION);
        }
        SetModuleTemperatureControl.OutputMsg outputMsg = new SetModuleTemperatureControl.OutputMsg();
        CompleteInstruction.SetModuleTemperatureControl.OutputMsg output = setModuleTemperatureControl.getOutput();
        ModuleTemperatureParam param = new ModuleTemperatureParam().formProto(output.getParam());
        outputMsg.setParam(param);
        this.setOutput(outputMsg);
        return this;
    }
}

